from rest_framework import serializers
import re

class SMSSendSerializer(serializers.Serializer):
    phone = serializers.CharField(max_length=11)
    purpose = serializers.CharField(max_length=20)

    def validate_phone(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式错误")
        return value

    def validate_purpose(self, value):
        valid_purposes = ['change_phone', 'user_login', 'reset_pwd']
        if value not in valid_purposes:
            raise serializers.ValidationError("无效的验证码用途")
        return value

class SMSVerifySerializer(serializers.Serializer):
    phone = serializers.CharField(max_length=11)
    code = serializers.CharField(max_length=6)
    purpose = serializers.CharField(max_length=20)

    def validate(self, data):
        if not re.match(r'^1[3-9]\d{9}$', data['phone']):
            raise serializers.ValidationError({"phone": "手机号格式错误"})
        if not data['code'].isdigit() or len(data['code']) != 6:
            raise serializers.ValidationError({"code": "验证码必须为6位数字"})
        return data